package cn.iocoder.yudao.module.infra.prometheus;

import cn.hutool.core.util.StrUtil;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Slf4j
@Component
public class LLMRequestTimeMetrics {
    // 预定义的SLO阈值数组
    private static final Duration[] SLO_THRESHOLDS = {
            Duration.ofMillis(100),
            Duration.ofMillis(300),
            Duration.ofMillis(500),
            Duration.ofMillis(700),
            Duration.ofMillis(1000),
            Duration.ofMillis(1500),
            Duration.ofMillis(2000),
            Duration.ofMillis(2500),
            Duration.ofMillis(3000),
            Duration.ofMillis(3500),
            Duration.ofMillis(4000),
            Duration.ofMillis(4500),
            Duration.ofMillis(5000)
    };

    @Resource
    private MeterRegistry registry;

    public LLMRequestTimeMetrics() {
    }

    public void recordSuccessRequestDuration(String path, Duration duration) {
        if (duration == null) {
            return;
        }

        if (StrUtil.isEmpty(path)) {
            path = "unknown";
        }

        final Timer timer = Timer.builder("llm.request.duration")
                .description("LLM 请求完成时间（秒）")
                .tag("protocol", "http")  // 可选：添加标签区分协议类型
                .tag("uri", path)
                .publishPercentiles(0.5, 0.75, 0.95, 0.99)
                .publishPercentileHistogram() // 发布直方图
                .serviceLevelObjectives(SLO_THRESHOLDS)
                .register(registry);

        // 记录耗时
        timer.record(duration);
    }

}
